package com.leoman.spinningmachine.tab1;

import android.Manifest;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.IBinder;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.leoman.helper.util.LogUtil;
import com.leoman.helper.util.ToastUtil;
import com.leoman.spinningmachine.R;
import com.leoman.spinningmachine.base.BaseFragment;
import com.leoman.spinningmachine.bean.DoorBean;
import com.leoman.spinningmachine.http.APIResponse;
import com.leoman.spinningmachine.http.WebServiceApi;
import com.leoman.spinningmachine.shake.NeedForSound;
import com.leoman.spinningmachine.shake.ShakeListener;
import com.leoman.spinningmachine.util.DialogUtils;
import com.leoman.spinningmachine.util.SharedPreferencesUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import cn.com.reformer.rfBleService.BleDevContext;
import cn.com.reformer.rfBleService.BleService;
import cn.com.reformer.rfBleService.OnCompletedListener;
import cn.com.reformer.rfBleService.OnPasswordWriteListener;

/**
 * 蓝牙
 */
public class BluetoothFragment extends BaseFragment {

    @BindView(R.id.doorName)
    TextView doorName;
    private ShakeListener mShakeListener;
    private ArrayList<byte[]> mWhiteList;
    private Integer openDoorResult = -1;
    private String token;
    private String macStr = "";

    public interface ShakeCallBack{
        void shakedOver();
    }
    @Override
    protected int getContentViewLayoutID() {
        return R.layout.fg_bluetooth;
    }

    @Override
    protected void initView(View view) {

        requestPermission();
        token = SharedPreferencesUtils.getInstance().getString("token");

        //搜索白名单 mac
        mWhiteList = (new ArrayList<byte[]>() {{
            add(new byte[]{0x36, 0x38, 0x37, 0x74, 0x47, 0x63, 0x72, 0x4E, 0x35});
            add(new byte[]{0x36, 0x4F, 0x70, 0x6A, 0x73, 0x54, 0x42, 0x41, 0x41});
            add(new byte[]{0x30, 0x56, 0x4C, 0x56, 0x7A, 0x34, 0x34, 0x58, 0x50});
            add(new byte[]{0x31, 0x6C, 0x66, 0x64, 0x73, 0x36, 0x73, 0x38, 0x73});
            add(new byte[]{0x30, 0x68, 0x75, 0x72, 0x55, 0x6D, 0x53, 0x72, 0x53});
            add(new byte[]{0x01, 0x11, 0x68, (byte) 0x93, (byte) 0xC4, 0x27, 0x5B, (byte) 0xC2, 0x6C});
        }});

        Intent bindIntent = new Intent(getActivity(), BleService.class);
        boolean bind = getActivity().bindService(bindIntent, mServiceConnection, Context.BIND_AUTO_CREATE);

        LogUtil.json("bind:"+bind);
//        LogUtil.json("versionName:"+getVersionName(getActivity()));
    }


    private void requestPermission() {
        if (Build.VERSION.SDK_INT >= 23 ) {
            int checkCallPhonePermission = ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.BLUETOOTH);
            if(checkCallPhonePermission != PackageManager.PERMISSION_GRANTED){
                ActivityCompat.requestPermissions(getActivity(),new String[]{Manifest.permission.BLUETOOTH,
                        Manifest.permission.BLUETOOTH_ADMIN,Manifest.permission.ACCESS_COARSE_LOCATION,
                Manifest.permission.ACCESS_FINE_LOCATION},100);
                return;
            }else{
                initShake();
            }
        }else{
            initShake();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if(requestCode == 100){
            if(grantResults[0] == PackageManager.PERMISSION_GRANTED){
                LogUtil.json("tongyi");
                initShake();
            }else{
                LogUtil.json("butongyi");
            }
        }
    }

    @Override
    protected void initData() {

    }

    private void initShake() {
        NeedForSound.getInstance().addSound(getActivity());
        mShakeListener = new ShakeListener(getActivity());
        mShakeListener.setOnShakeListener(new ShakeListener.OnShakeListenerCallBack() {
            @Override
            public void onShake() {
                if(canShaked){
                    canShaked = false;
                    LogUtil.json("摇一摇");
                    DialogUtils.getInstance().show(getActivity());
//                    NeedForSound.getInstance().playStartSound();
                    if (rfBleKey!=null){
                        ArrayList<BleDevContext> lst = rfBleKey.getDiscoveredDevices();
                        for (BleDevContext dev:lst){
                            StringBuffer stringBuffer = new StringBuffer();
                            stringBuffer.append(bytesToString(dev.mac));
                            macStr = stringBuffer.toString().toUpperCase();
                            break;
                        }
                        openDoor(macStr);
                    }else{
                        noDoorDevice();
                    }
                }
            }
        });

    }

    private boolean canShaked = true;

    private void openDoor(String macStr) {
        LogUtil.json("mac:"+macStr);
        if(!TextUtils.isEmpty(macStr)){
            WebServiceApi.getInstance().getDoorName(macStr,this,1);
            openDoorResult = rfBleKey.openDoor(stringToBytes(macStr),
                    Integer.decode("5"),
                    "31313131313131313131313131313131"); // 默认密码
        }else{
            noDoorDevice();
        }
    }

    @Override
    public void OnSuccessData(APIResponse apiResponse, Integer tag) {
        super.OnSuccessData(apiResponse, tag);
        if(tag == 1){
            List<DoorBean> lists = apiResponse.data.list;
            if (lists!=null&&lists.size()>0){
                DoorBean bean = lists.get(0);
                if(bean!=null&&doorName!=null){
                    doorName.setText("门锁信息:"+bean.getName());
                }
            }
        }else if(tag == 2){
            LogUtil.json("222222222");
        }
    }

    private BleService mService;
    private BleService.RfBleKey rfBleKey;

    private final ServiceConnection mServiceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName className,
                                       IBinder rawBinder) {
            mService = ((BleService.LocalBinder) rawBinder).getService();
            rfBleKey = mService.getRfBleKey();
            rfBleKey.init(null);//mWhiteList
            rfBleKey.setOnCompletedListener(new OnCompletedListener() {
                @Override
                public void OnCompleted(byte[] bytes, int i) {
                    final int result = i;
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            canShaked = true;
                            LogUtil.json("macStr:::"+macStr);
                            if(!TextUtils.isEmpty(macStr)){
                                String status = "";
                                if(0 == result){
                                    status = "1";
                                }else{
                                    status = "2";
                                }
                                WebServiceApi.getInstance().addOpenDoorHistory(token,macStr,status,BluetoothFragment.this,2);
                            }
                            DialogUtils.getInstance().cancel();
                            LogUtil.json("开门结果："+result);
                            switch (result) {
                                case 0:
                                    ToastUtil.showToast(getActivity(),"开门成功", Toast.LENGTH_SHORT);
                                    mShakeListener.stop();
                                    break;
                                case 1:
                                    ToastUtil.showToast(getActivity(),"密码错误", Toast.LENGTH_SHORT);
                                    break;
                                case 2:
                                    ToastUtil.showToast(getActivity(),"蓝牙断开或连接失败", Toast.LENGTH_SHORT);
                                    break;
                                case 3:
                                    ToastUtil.showToast(getActivity(),"连接超时", Toast.LENGTH_SHORT);
                                    break;
                            }
                        }
                    });
                }
            });


            rfBleKey.setOnPasswordWriteListener(new OnPasswordWriteListener() {
                @Override
                public void OnPasswordWrite(byte[] bytes, int i) {
                    final int result = i;
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            LogUtil.json("设置密码结果："+result);
                            if (result == 0) {
                                ToastUtil.showToast(getActivity(),"设置密码成功", Toast.LENGTH_SHORT);
                            } else if (result == 1) {
                                ToastUtil.showToast(getActivity(),"设置密码失败", Toast.LENGTH_SHORT);
                            }
                        }
                    });
                }
            });

            rfBleKey.setOnBleDevListChangeListener(new BleService.OnBleDevListChangeListener() {
                @Override
                public void onNewBleDev(BleDevContext bleDevContext) {
                    //发现新设备
                }

                @Override
                public void onUpdateBleDev(BleDevContext bleDevContext) {
                    //设备更新
                }
            });
        }

        @Override
        public void onServiceDisconnected(ComponentName classname) {
            mService = null;
        }
    };

    public void noDoorDevice(){
        DialogUtils.getInstance().cancel();
        canShaked = true;
        ToastUtil.showToast(getActivity(),"未找到门禁设备!",Toast.LENGTH_SHORT);
    }

    private void setPwd(String macStr,String pwd){
        rfBleKey.setDevPassword(stringToBytes(macStr),pwd);
    }

    public static byte[] stringToBytes(String outStr){
        if (outStr.length()!=18)
            return null;
        int len = outStr.length()/2;
        byte[] mac = new byte[len];
        for (int i = 0; i < len; i++){
            String s = outStr.substring(i*2,i*2+2);
            if (Integer.valueOf(s, 16)>0x7F) {
                mac[i] = (byte)(Integer.valueOf(s, 16) - 0xFF - 1);
            }else {
                mac[i] = Byte.valueOf(s, 16);
            }
        }
        return mac;
    }

    public static String bytesToString(byte b[]) {
        StringBuffer hexString = new StringBuffer();
        for (int i = 0; i < b.length; i++) {
            String plainText = Integer.toHexString(0xff & b[i]);
            if (plainText.length() < 2)
                plainText = "0" + plainText;
            hexString.append(plainText);
        }
        return hexString.toString().toUpperCase();
    }

//    public static String getVersionName(Context context) {
//        return getPackageInfo(context).versionName;
//    }
//
//    private static PackageInfo getPackageInfo(Context context) {
//        PackageInfo pi = null;
//        try {
//            PackageManager pm = context.getPackageManager();
//            pi = pm.getPackageInfo(context.getPackageName(),
//                    PackageManager.GET_CONFIGURATIONS);
//            return pi;
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return pi;
//    }

    @Override
    public void onPause() {
        if(rfBleKey!=null){
            rfBleKey.free();
        }
        getActivity().unbindService(mServiceConnection);
        super.onPause();
    }
}
